# coding=utf-8
"""
Copyright 2019-2020 Fang Jin Biao

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# @Time    : 2020/7/19 19:35
# @Author  : Fang Jin Biao
# @Email   : 215466914@qq.com
# @File    : knowledge_acquire_api.py
# @Project : SnowAdminWeb
import datetime

from flask import Blueprint, request, session, g
from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser

from webapp.config.api_utils import build_params, oper_log, check_auth
from webapp.dto_mapper import paper_help_page_fields, paper_help_fields
from webapp.models import PaperHelp, db
from webapp.schema import PaperHelpSchema, falsy
from webapp.service.paper_help_service import PaperHelpService
from webapp.tools import format_date, download_excel_knowledge, connect_server
from collections import OrderedDict
import json
from webapp.quartz_utils.quartz_manage import scheduler
import requests
import re
import threading
from sqlalchemy import or_
paper_help_app = Blueprint('paper_help', __name__, url_prefix='/api/PaperHelp')
paper_help_api = Api(paper_help_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)


@paper_help_api.resource('', '/')
class AppAPI(Resource):
    @oper_log('查询文献求助', request)
    @marshal_with(paper_help_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = build_params(params)
        data = json.loads(g.get("user"))
        user_id = data["id"]
        pagination = PaperHelpService.query_all(user_id=user_id, **params_dict)
        return pagination

    @oper_log('新增文献求助', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = PaperHelpSchema()
        curr_data = schema.load(params, unknown="exclude")
        data = json.loads(g.get("user"))
        curr_data.user_id = data["id"]
        return PaperHelpService.create(curr_data=curr_data)

    @oper_log('修改文献求助', request)
    def put(self):
        params = request.get_json()
        schema = PaperHelpSchema()
        if params.get("is_read") is None:
            params["is_read"] = False
        curr_data = schema.load(params, unknown="exclude")
        data = json.loads(g.get("user"))
        curr_data.user_id = data["id"]
        PaperHelpService.update(curr_data=curr_data)

    @oper_log('删除文献求助', request)
    def delete(self):
        ids = request.get_json()
        PaperHelpService.delete(ids=ids)

@paper_help_api.resource('/getallunread')
class getallunread(Resource):
    @marshal_with(paper_help_page_fields)
    def get(self):
        query = []
        data = json.loads(g.get("user"))
        query.append(PaperHelp.user_id == data["id"])
        query.append(or_(PaperHelp.result.contains("paperbucket"),(PaperHelp.result.contains("sci-hub"))))
        query.append(or_(PaperHelp.is_read==False,PaperHelp.is_read.is_(None)))
        alldata = PaperHelp.query.filter(*query).all();
        print(alldata)
        return  {"items":alldata, "total":len(alldata)}

@paper_help_api.resource('/batch')
class paperHelpBatch(Resource):
    @oper_log('批量新增文献求助', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        paramsList = request.get_json()
        for params in paramsList:
            schema = PaperHelpSchema()
            curr_data = schema.load(params, unknown="exclude")
            data = json.loads(g.get("user"))
            curr_data.user_id = data["id"]
            PaperHelpService.create(curr_data=curr_data)

    @oper_log('批量修改文献求助', request)
    def put(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        paramsList = request.get_json()
        for params in paramsList:
            schema = PaperHelpSchema()
            if params.get("is_read") is None:
               params["is_read"] = False
            curr_data = schema.load(params, unknown="exclude")
            data = json.loads(g.get("user"))
            curr_data.user_id = data["id"]
            PaperHelpService.update(curr_data=curr_data)


@paper_help_api.resource('/<int:_id>')
class GetPaperHelpById(Resource):
    @oper_log('根据ID查询文献求助', request)
    @marshal_with(paper_help_fields)
    def get(self, _id):
        data = json.loads(g.get("user"))
        user_id = data["id"]
        data = PaperHelpService.find_by_id(id=_id, user_id=user_id)
        return data


def worker(group_i, key):
    r = requests.post("http://1.13.176.116:19090/paper/get-status", json=group_i)
    paramsList = r.json()
    for index, params in enumerate(paramsList):
        if not params.get("id"):
            params["id"] = group_i[index]["id"]
        schema = PaperHelpSchema()
        if params.get("is_read") is None:
            params["is_read"] = False
        curr_data = schema.load(params, unknown="exclude")
        if curr_data.result:
            PaperHelpService.update(curr_data=curr_data)


@scheduler.task(id='flashPaperHelpStatus', trigger='interval',seconds=5*60)
def task():
    PaperHelpData = PaperHelp.query.all()
    data = []
    now = datetime.datetime.now()
    termiatedId=[]
    for item in PaperHelpData:
        isNotvalidUrl = (item.result is None or (item.result is not None and not re.search(r'(paperbucket|sci-hub)', item.result))) if re.search(r'(10\.)', item.doi) else False
        if isNotvalidUrl:
            if now - item.create_time  < datetime.timedelta(seconds=24*60*60) :
                postBodyJson = {"id": item.id, "doi": item.doi, "task_type": item.task_type,
                            "task_status": item.task_status, "task_id": item.task_id}
                if item.result is not None:
                    postBodyJson["result"] = item.result
                data.append(postBodyJson)
            else:
                termiatedId.append(item.id)


                # PaperHelpService.update(curr_data=paperHelp)
    if len(termiatedId):
        for id in termiatedId:
            paperHelp = PaperHelp.query.filter_by(id=id).first()
            paperHelp.task_status = "terminated"
            db.session.commit()
            db.session.close()
    if len(data) == 0:
        return
    print("scheduler.task:::::::::::")
    print(data)
    group = [data[i:i + 5] for i in range(0, len(data), 5)]
    threads = []
    for key, group_i in enumerate(group):
        thread = threading.Thread(target=worker, args=(group_i, key))
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()
